/* TODO
  new chart: performances per month/year, #concerts, total songs, unique songs
  DONE: add controls for songs by year to allow selection of writer: Jewel, JewelOther, Other
  DONE: tidy up the {} matching stuff
  DONE: add the code for the cbl calendar
  DONE: display songs when clicking pie segment
  DONE: dispaly songs when click point on area graph


*/
/* BUGS
  FIXED: sort out the implementation of the calendar eg menus are being bound twice
*/

/*
 to compress...
 d:
 cd TalkTalk\piecesofuk\Javascript
 java -jar D:\Programming\Javascript\yuicompressor-2.3.5\build\yuicompressor-2.3.5.jar visualizations.js -o visualizations.min.js
*/

if (typeof PIECESOFUK == "undefined") {
	var PIECESOFUK = {};
}

PIECESOFUK.visualizationsPtr = null;

PIECESOFUK.initVisualizations = function() {

	$("body").show();
	$(".aDialog").hide();
	if (PIECESOFUK.visualizationsPtr == null) PIECESOFUK.visualizationsPtr = new PIECESOFUK.visualizations();
	PIECESOFUK.visualizationsPtr.display();
}

PIECESOFUK.googleChartsLoaded = false;
google.load("visualization", "1", {packages:["piechart", "areachart"]});
google.setOnLoadCallback( function() { PIECESOFUK.googleChartsLoaded = true;});

PIECESOFUK.visualizations = function() {

	$(".aVisDescription").hide();
	$("#visOverview").show()

	var charts = this;
	$("#visOptions").val("blank");
	this.albumTotals = {};
	this.albumColors = {"Pieces of You": "#ffa6a6", "Spirit" : "#ffd081", "This Way" : "#ffff7e",
										 "0304" : "#6aff6a", "Goodbye Alice...": "#8b8bff",
										 "Perfectly Clear" : "#ca63ff", "Lullaby" : "#e9ddaf", "Other" : "#f3c4f3",
										 "unreleased" : "#cce2cd", "not found" : "#a7eee1"};

  this.writerColors = {"all": "#0000ff", "Jewel": "#00ff00", "JewelOther": "#FFA500", "Other": "#ff0000"};

/* move to POUKindex.js
PIECESOFUK.albumMap = {"POY" : "Pieces of You",
                       "Spirit" : "Spirit",
											 "ThisWay" : "This Way",
											 "0304" : "0304",
											 "GBAIW" : "Goodbye Alice...",
											 "PC" : "Perfectly Clear",
											 "Lullaby" : "Lullaby",
											 "Other" : "Other",
											 "unreleased" : "unreleased",
											 "not found" : "not found"};
*/

PIECESOFUK.albumFullName = {"Goodbye Alice..." : "Goodbye Alice In Wonderland"}; // the charts don't display well with long names

  $("#visOptions").change( function() {
		if ( $(this).val()  == "setlists" ) charts.calendarCharts();
		else if ( $(this).val()  == "songsByYear" ) PIECESOFUK.songsByYear();
	});

	$(".visOptionImg").click( function() {
		if ( $(this).attr("src") == "Graphics/visSongsByYear.gif" ) PIECESOFUK.songsByYear();
		else if ( $(this).attr("src") == "Graphics/visAlbumsBySetlists.gif" ) charts.calendarCharts();
	});

	this.display = function() {
		if ( $("#visualizations").hasClass("ui-dialog-content") ) {
			if ($("#visualizations").dialog("isOpen")) $("#visualizations").dialog("moveToTop");
			else $("#visualizations").dialog("open");
		}
		else {
			$("#visualizations").dialog({width: 500, height: 400, title: "Visualizations", close: this.close, focus: this.focus});
			$("#ui-dialog-title-visualizations")
			   .prepend('<img class="infoViewTitleImg" src="Graphics/visualizations.png" width="16" height="16" alt="icon">')
         .parent()
				 .css("paddingLeft", "3px");
		}
	}

	this.displaySummary = function() {
		if ( $("#visSummary").hasClass("ui-dialog-content") ) {
			if ($("#visSummary").dialog("isOpen")) $("#visSummary").dialog("moveToTop");
			else $("#visSummary").dialog("open");
		}
		else $("#visSummary").dialog({width: 450, height: 300, title: "Setlist Summary", close: this.close, focus: this.focus});

	}

	this.calendarCharts = function() {
		$("#visDiv").html("");
		$(".visSubControl").hide();
		$("#visHead").html("<b>Jewel albums by setlist</b>")
	  $(".aVisDescription").hide();
	  $("#visAlbumSetlists").show()

//	  if ( PIECESOFUK.feeds == undefined ) PIECESOFUK.initCalendar();

		if ( PIECESOFUK.feeds == undefined ) PIECESOFUK.feeds = new Array;
		if (PIECESOFUK.feeds["calendar"] == undefined) {
      PIECESOFUK.feeds["calendar"] = new PIECESOFUK.calendar();
  	  setTimeout(PIECESOFUK.controller, 1000);
      PIECESOFUK.initCalendarView();
		}


		charts.display();
		if (!PIECESOFUK.songs) PIECESOFUK.loadSongs();
		$(".cbmEntry.aConcert").live("click", function() {
		  $(".aVisDescription").hide();
			var date = "";
			date = $(this).parent().prev().text() + " " + PIECESOFUK.months[$("#calSelectMonth").val()-1] +
			                                                                           " " + $("#calSelectYear").val();
			charts.accumulateSongData($(this), date);
		});
		$(".cblEntry.aConcert").live("click", function() {
		  $(".aVisDescription").hide();
			var date = "";
			var id = $(this).parent().prev().attr("id");
			var splitDate = id.match(/d(\d\d)m(\d\d)y(\d{4})/);
			date = splitDate[1] + " " + PIECESOFUK.months[splitDate[2] - 1] + " " + splitDate[3];
			charts.accumulateSongData($(this), date);
		});
	}

	this.accumulateSongData = function($this, date) {
    charts.songsInAlbum = [];

//	  var a = $this.attr("title").match(/setlist: \[(.*)\]/);
	  var a = $this.attr("title").match(/setlist: \[(.*?)\]/);
	  if (a) {
		  a = a[1];
		  charts.resetChartData();
/*
 			var idx;
			while ( (idx = a.indexOf("{")) != -1 ) {
				a = a.substr(0, idx) + a.substr( a.indexOf("}", idx) + 1 );
			}
*/
		  var songs = a.replace(/ Encore:/, "").split("; ");
		  for (var i = 0; i < songs.length; i++) {
//				songs[i] = songs[i].replace(/^ /, "").replace(/ $/, "");
				var songTitle = songs[i];
			  var album = "not found";
				if ( songs[i].search(/ {/) != -1 ) songs[i] = songs[i].replace(/ {.*}/, "");
			  if ( songs[i].search(/^The /) == 0 ) songs[i] = songs[i].replace(/^The /, "") + ", The"; // change "The New Wild West" into "New Wild West, The"
			  if ( songs[i].search(/^A /) == 0 ) songs[i] = songs[i].replace(/^A /, "") + ", A"; // change "A Boy Needs A Bike" into "Boy Needs A Bike, A"
			  if (PIECESOFUK.songs[songs[i]] != undefined) {
				  var album = "unreleased";
				  var getAlbum = PIECESOFUK.songs[songs[i]].match(/Album-(\w*)/);
				  if ( getAlbum ) {
					  album = PIECESOFUK.albumMap[getAlbum[1]]
				  }
			  }
			  else $("#visErrors").append(" " + songs[i] + " not found");
				/*
				if (charts.songsInAlbum[album] == undefined) charts.songsInAlbum[album] = songs[i];
				else charts.songsInAlbum[album] += "; " + songs[i];
				*/
				if (charts.songsInAlbum[album] == undefined) charts.songsInAlbum[album] = songTitle;
				else charts.songsInAlbum[album] += "; " + songTitle;
			  charts.albumTotals[album]++;
		  }
//		PIECESOFUK.drawChart(date + " " + $this.text().replace(/^\d\d:\d\d /, ""));
		  charts.drawChart(date + " " + $this.data("where"));
    }
		else alert("No setlist found for this event");
  }

	this.resetChartData = function() {
	  $("#visDiv").html("");
	  $("#visSongs").html("");
	  $("#visSummary").html("");
	  $("#visErrors").html("");
	  charts.albumTotals = {};
    for (var i in PIECESOFUK.albumMap) {
	    charts.albumTotals[ PIECESOFUK.albumMap[i] ] = 0;
    }
  }

  this.drawChart = function(heading) {
		if ($("#visualizations").dialog("isOpen")) $("#charts").dialog("moveToTop");
		else $("#visualizations").dialog("open");
    var data = new google.visualization.DataTable();
	  if (PIECESOFUK.googleChartsLoaded) {
		  var numRows = 0;
		  for (var i in charts.albumTotals) {
			  if (charts.albumTotals[i] > 0) ++numRows;
//			  $("#chartSummary").append(i + charts.albumTotals[i] );
		  }

      data.addColumn('string', 'Album');
      data.addColumn('number', '#songs');
      data.addRows(numRows);
		  var count = 0;
		  var colorArray = new Array;
//			var GBAIW = false;
		  for (var i in charts.albumTotals) {
			  if ( charts.albumTotals[i] > 0 ) {
//					if ( i == "Goodbye Alice In Wonderland") GBAIW = true;
          data.setValue(count, 0, i);
          data.setValue(count, 1, charts.albumTotals[i]);
				  colorArray[count] = charts.albumColors[i]
			    ++count;
			  }
		  }
//      var chart = new google.visualization.PieChart(document.getElementById('chartDiv'));
      var chart = new google.visualization.PieChart($("#visDiv")[0]);

      google.visualization.events.addListener(chart, 'select', function() {
				if (this.getSelection()[0].column != undefined) {
				  var album  = data.getValue(this.getSelection()[0].row, 0);
			    charts.displaySummary();

				  if (album == "unreleased") $("#visSummary")
					  .html("The unreleased songs that Jewel performed were...<br><br>" + charts.songsInAlbum[album]);
					else if (album == "Other") $("#visSummary")
					  .html("The songs Jewel performed from other albums, eg compilations or soundtracks, were...<br><br>" + charts.songsInAlbum[album]);
				  else {
						var albumTxt = album;
						if (PIECESOFUK.albumFullName[album] != undefined) albumTxt = PIECESOFUK.albumFullName[album];
						$("#visSummary")
					     .html("The songs Jewel performed from " + albumTxt + " were...<br><br>" + charts.songsInAlbum[album]);
					}
				}
			});
//			var width = 450, height = 250;
//			if (GBAIW) {width = 550; }
//      chart.draw(data, {width: width, height: height, is3D: true, title: heading,
      chart.draw(data, {width: $("#visualizations").width() - 10, height: $("#visualizations").height() - 40, is3D: true, title: heading,
							 backgroundColor: "#f9f9f9", colors: colorArray, legend : "bottom",
							 borderColor: "#888888", focusBorderColor: "#111111", enableTooltip: false});
		  $("#visualizations").dialog("moveToTop");
	  }
  }

	this.focus = function() {
		$(".aControl").hide();
		$("#visControls").show();
	}

	this.close = function() {
		var zIndex = 0, $topMost = null;
    $(".aDialog").parent(".ui-dialog:visible").each( function() {
			if ( $(this).css("zIndex") > zIndex ) {
				zIndex = $(this).css("zIndex");
				$topMost = $(this).children(".aDialog");
			}
		});
		if ($topMost) {
			if ( $topMost.attr("id") == "calView" ) PIECESOFUK.feeds["calendar"].focus();
		}
	}
}

PIECESOFUK.songsByYear = function() {
	songsByYear = this;

	this.writerColors = {"all": "#0000ff", "Jewel": "#00ff00", "JewelOther": "#FFA500", "Other": "#ff0000"}
	$("#visDiv").html("");
	$(".visSubControl").hide();
	$("#visSBYoptsForm").show();
	$("#visHead").html("<b>Jewel songs by Year</b>");
	$(".aVisDescription").hide();
	$("#visSongsByYearDesc").show()
	/*
	$("#visDiv").text("This chart will give totals by year of the number of songs Jewel has written or first performed in \
									that year. So you can see at a glance when Jewel was most prolific and when she was taking a rest. \
									You can view graphs of songs written just by Jewel, by Jewel and someone else or songs \
									written by others. Select the options in the control bar at the top and click Draw. \
									If you want a larger view of the graphs then resize this window and then click Draw again. \
									If you click on a point within the graph then you will see all the songs for that particular year.")
	*/
  $("#visDrawButton").click( function() {
		$(".aVisDescription").hide();
		songsByYear.draw();
	});


  this.yearTotals = {};
  this.songTotals = {};
	this.numYears = 0;
	this.songCount = 0;

	this.accumulateData = function() {
  	if (!PIECESOFUK.songs) PIECESOFUK.loadSongs();
		songsByYear.songTotals["all"] = new Array;
    for (song in PIECESOFUK.songs) {
			++songsByYear.songCount;
      var year = PIECESOFUK.songs[song].match(/Year-(\d{4})/)[1];
      var writer = PIECESOFUK.songs[song].match(/Writer-([a-zA-Z]*)/)[1];
      if ( songsByYear.songTotals[writer] == undefined ) songsByYear.songTotals[writer] = new Array;
      songsByYear.songTotals[writer].push(year);
		  songsByYear.songTotals["all"].push(year);
    }
		songsByYear.yearTotals["all"] = {};

    for (var i in songsByYear.songTotals) {
      songsByYear.songTotals[i].sort();
      songsByYear.yearTotals[i] = {};
      for (var j = 0; j < songsByYear.songTotals[i].length; ++j) {
        if (songsByYear.yearTotals[i][songsByYear.songTotals[i][j]] == null) {
					if (i == "all") ++songsByYear.numYears;
					songsByYear.yearTotals[i][songsByYear.songTotals[i][j]] = 1;
				}
        else ++songsByYear.yearTotals[i][songsByYear.songTotals[i][j]];
      }
    }

	}

	songsByYear.accumulateData();

	this.draw = function() {
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Year');
		var colorArray = new Array;
		var count = 0;
		if ( $("#visSBYWriterJewel").is(":checked") ) {
			data.addColumn('number', 'Jewel');
			colorArray[count++] = songsByYear.writerColors["Jewel"];
		}
		if ( $("#visSBYWriterJewelOther").is(":checked") ) {
			data.addColumn('number', 'JewelOther');
			colorArray[count++] = songsByYear.writerColors["JewelOther"];
		}
		if ( $("#visSBYWriterOther").is(":checked") ) {
			data.addColumn('number', 'Other');
			colorArray[count++] = songsByYear.writerColors["Other"];
		}
		data.addColumn('number', 'all');
		colorArray[count++] = songsByYear.writerColors["all"];


		data.addRows(songsByYear.numYears);
    var row = 0;

		for ( var year in songsByYear.yearTotals["all"]) {
			if ( songsByYear.yearTotals["Jewel"][year] == undefined) songsByYear.yearTotals["Jewel"][year] = 0;
			if ( songsByYear.yearTotals["JewelOther"][year] == undefined) songsByYear.yearTotals["JewelOther"][year] = 0;
			if ( songsByYear.yearTotals["Other"][year] == undefined) songsByYear.yearTotals["Other"][year] = 0;
//	console.log(year)
			var column = 0;
		  data.setValue(row, column++, year);
			var allTotal = 0;
		  if ( $("#visSBYWriterJewel").is(":checked") ) {
				allTotal += songsByYear.yearTotals["Jewel"][year];
				data.setValue(row, column++, songsByYear.yearTotals["Jewel"][year]);
			}
		  if ( $("#visSBYWriterJewelOther").is(":checked") ) {
				allTotal += songsByYear.yearTotals["JewelOther"][year];
				data.setValue(row, column++, songsByYear.yearTotals["JewelOther"][year]);
			}
		  if ( $("#visSBYWriterOther").is(":checked") ) {
				allTotal += songsByYear.yearTotals["Other"][year];
				data.setValue(row, column++, songsByYear.yearTotals["Other"][year]);
			}
//		  data.setValue(row, column++, songsByYear.yearTotals["all"][year]);
		  data.setValue(row, column++, allTotal);
			++row;
		}

		$("#visHead").html("");
		$("#visDiv").html("");
		$("#visFooter").html("There are currently " + songsByYear.songCount + " songs in the " +
													"<a href='songs.html'>Jewel song database</a>");
		var chart = new google.visualization.AreaChart($("#visDiv")[0]);

    google.visualization.events.addListener(chart, 'select', function() {
			if (this.getSelection()[0].row != undefined) {
			  PIECESOFUK.visualizationsPtr.displaySummary();
			  var which = data.getColumnLabel(this.getSelection()[0].column);
			  var year = data.getValue( this.getSelection()[0].row, 0 );
			  var num = data.getValue( this.getSelection()[0].row, this.getSelection()[0].column );
			  var s = "";
			  for ( var i in PIECESOFUK.songs) {
				  if (PIECESOFUK.songs[i].indexOf("Year-"+year) != -1 ) {
					  if (which == "all") s += i + "; ";
//					else if ( PIECESOFUK.songs[i].indexOf("Writer-"+which) != -1 ) s += i + "; ";
					  else {
						  var r = new RegExp("Writer-" + which + "\\b");
					    if ( PIECESOFUK.songs[i].match(r) ) s += i + "; ";
					  }
				  }
			  }

			  $("#visSummary").html("Of the " + songsByYear.songCount + " Jewel songs in the database, the following " + num +
															" written by " + which + " " +
														 (num > 1 ? " were" : " was") + " first performed or written in " + year + "..." + "<br><br>");

			  $("#visSummary").append(s.slice(0, -2));
			}

		});
		chart.draw(data, {width: $("#visualizations").width() - 10, height: $("#visualizations").height() - 40, legend: 'bottom',
							 title: 'Total number of Jewel songs by Year', backgroundColor: "#f9f9f9", enableTooltip: false,
							 colors: colorArray});



	}

}
